"use client";
import { useParams } from "next/navigation";
import { useState } from "react";
import { getProject, getResultsByProjectId, updateProject, updateResult, ResultType } from "@/controller/project";
import { toast } from "sonner";
import { createLead, deleteLead } from "@/controller/leads";
import { useEffect } from "react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import useSWR, { mutate } from 'swr';
import { Loader2, MoreVertical, Edit, Trash2, Search, Plus, Check, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useTranslations } from 'next-intl';
import { Project } from '@/controller/project';
import { Badge } from '@/components/ui/badge';

export default function Result({ project }: { project: Project }) {
  const t = useTranslations('project');
  const commonT = useTranslations('common');
  const [isLoading, setIsLoading] = useState(true);
  const [matchingRulesKeys, setMatchingRulesKeys] = useState<string[] | null>(null);
  const [searchScoreKeys, setSearchScoreKeys] = useState<string[] | null>(null);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [editColumnLabel, setEditColumnLabel] = useState('');
  const [currentColumnName, setCurrentColumnName] = useState('');
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [filteredData, setFilteredData] = useState<any[]>([]);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [newColumnLabel, setNewColumnLabel] = useState('');
  const [loadingState, setLoadingState] = useState<{ resultId: string } | null>(null);
  const params = useParams();
  const id = params.id as string;
  // 处理表格搜索
  const handleTableSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    const query = e.target.value;
    setSearchQuery(query);

    // 如果查询为空，显示所有数据
    if (!query.trim() || !resultsData?.data) {
      setFilteredData(resultsData?.data || []);
      return;
    }

    // 过滤数据
    const filtered = resultsData.data.filter((item: any) => {
      // 搜索所有搜索结果字段
      const searchMatches = Object.values(item.search_result || {}).some(
        (value: any) => String(value).toLowerCase().includes(query.toLowerCase())
      );

      // 搜索所有匹配分数字段
      const matchMatches = Object.values(item.match_score || {}).some(
        (value: any) => String(value).toLowerCase().includes(query.toLowerCase())
      );

      return searchMatches || matchMatches;
    });

    setFilteredData(filtered);
  };

  // 打开编辑列对话框
  const openEditColumnDialog = (columnName: string) => {
    setCurrentColumnName(columnName);
    setEditColumnLabel(columnName);
    setIsEditDialogOpen(true);
  };

  // 打开删除列对话框
  const openDeleteColumnDialog = (columnName: string) => {
    setCurrentColumnName(columnName);
    setIsDeleteDialogOpen(true);
  };

  // 处理编辑列
  const handleEditColumn = async () => {
    const newMatchingRulesKeys = matchingRulesKeys?.map((key) => key === currentColumnName ? editColumnLabel : key);
    if (newMatchingRulesKeys) {
      const { data, error } = await updateProject(id, { matching_rules: newMatchingRulesKeys })
      if (error || !data) {
        toast.error('edit column failed');
        return;
      }
      setMatchingRulesKeys(newMatchingRulesKeys)
    } else {
      toast.error('edit column failed');
    }
    setIsEditDialogOpen(false);
  };

  // 处理删除列
  const handleDeleteColumn = async () => {
    const newMatchingRulesKeys = matchingRulesKeys?.filter((key) => key !== currentColumnName);
    if (newMatchingRulesKeys) {
      const { data, error } = await updateProject(id, { matching_rules: newMatchingRulesKeys })
      if (error || !data) {
        toast.error('delete column failed');
        return;
      }
      setMatchingRulesKeys(newMatchingRulesKeys)
    } else {
      toast.error('delete column failed');
    }
    setIsDeleteDialogOpen(false);
  };
  // 处理添加新列
  const handleAddColumn = async () => {
    // 使用空数组作为默认值，避免null
    const currentKeys = matchingRulesKeys || [];
    const newMatchingRulesKeys = [...currentKeys, newColumnLabel];

    const { data, error } = await updateProject(id, { matching_rules: newMatchingRulesKeys })
    if (error || !data) {
      toast.error('edit column failed');
      return;
    }
    setMatchingRulesKeys(newMatchingRulesKeys)
    setIsDialogOpen(false);
  };

  const handleAnnotation = async (item: ResultType, annotation: 'compliant' | 'non-compliant') => {
    setLoadingState({ resultId: item.result_id });
    try {
      // 将compliant/non-compliant映射到API的APPROVED/REJECTED
      const verdict = annotation === 'compliant' ? 'APPROVED' : 'REJECTED';
      // 如果已经是相同的标注，则设为PENDING
      const user_verdict = verdict === item.user_verdict ? 'PENDING' : verdict;

      // 乐观更新：立即更新本地状态
      const originalVerdict = item.user_verdict;
      item.user_verdict = user_verdict;

      // 触发SWR重新获取数据（可选，如果要立即反映在UI上）
      mutate(`/api/results/${id}`, undefined, { revalidate: false });

      // 处理lead创建或删除
      if (user_verdict === 'APPROVED') {
        const { data: leadData, error: leadError } = await createLead({
          project_id: id,
          type: project.search_objective,
          target_id: item.creator_id,
          result_id: item.result_id
        })
        if (leadError || !leadData) {
          // 恢复原始状态
          item.user_verdict = originalVerdict;
          mutate(`/api/results/${id}`, undefined, { revalidate: false });
          toast.error('Failed to create lead');
          return;
        }
      } else if (originalVerdict === 'APPROVED') {
        const { data: leadData, error: leadError } = await deleteLead(item.result_id)
        if (leadError || !leadData) {
          // 恢复原始状态
          item.user_verdict = originalVerdict;
          mutate(`/api/results/${id}`, undefined, { revalidate: false });
          toast.error('Failed to delete lead');
          return;
        }
      }

      // 发送API请求更新后端数据
      const { data, error } = await updateResult(item.result_id, { user_verdict })
      if (error || !data) {
        // 恢复原始状态
        item.user_verdict = originalVerdict;
        mutate(`/api/results/${id}`, undefined, { revalidate: false });
        toast.error('Failed to update annotation');
        return;
      }

      // 成功后重新验证数据
      mutate(`/api/results/${id}`);
      toast.success('Annotation updated successfully');
    } catch (error) {
      toast.error('Failed to update annotation');
    } finally {
      setLoadingState(null);
    }
  };

  useEffect(() => {
    // 当路由参数加载完成后，可以在这里处理与id相关的逻辑
    if (!id) {
      return;
    }
    const initProject = async () => {
      setIsLoading(true);
      try {
        const { data: project, error } = await getProject(id);
        if (error || !project) {
          toast.error('get project failed');
          return;
        }
        setMatchingRulesKeys(project.matching_rules)
      } catch (error) {
        console.error('获取项目失败:', error);
      } finally {
        setIsLoading(false);
      }
    }
    initProject();
  }, [id]);

  // 使用SWR轮询获取结果数据
  const { data: resultsData, error: resultsError } = useSWR(
    id ? `/api/results/${id}` : null,
    () => getResultsByProjectId(id),
    {
      refreshInterval: 3000, // 每3秒轮询一次
      dedupingInterval: 1000 // 1秒内相同的请求只发送一次
    }
  );

  useEffect(() => {
    if (resultsData && resultsData.data && matchingRulesKeys) {
      const data = resultsData.data;
      // 设置搜索结果的键
      if (data.length > 0) {
        setSearchScoreKeys(Object.keys(data[0].search_result));
      }

      // data.forEach((item: any) => {
        // 处理匹配分数数据
        // const score: string[] = []
        // if (matchingRulesKeys) {
        //   matchingRulesKeys.forEach((key: string) => {
        //     score.push(item.match_score[key] || '');
        //   });
        // }

        // 处理搜索结果数据
        // const searchResult: string[] = []
        // if (item.search_result) {
        //   Object.keys(item.search_result).forEach((key: string) => {
        //     searchResult.push(item.search_result[key]);
        //     console.log("🚀 ~ file: result.tsx:268 ~ item.search_result[key]:", key)
        //     console.log("🚀 ~ file: result.tsx:268 ~ item.search_result[key]:", item.search_result[key])
        //     console.log("🚀 ~ file: result.tsx:268 ---------------------------")
        //   });
        // }
      // });

      // 初始化过滤数据或应用当前搜索查询
      if (searchQuery.trim()) {
        handleTableSearch({ target: { value: searchQuery } } as React.ChangeEvent<HTMLInputElement>);
      } else {
        setFilteredData(data);
      }
    }
  }, [resultsData, matchingRulesKeys]);

  return (
    <div className="mt-6 space-y-3">
      <div className="flex items-center justify-between">
        <div className="relative flex items-center w-1/3">
          <Search className="absolute left-2 h-4 w-4 text-gray-400" />
          <Input
            placeholder={t('searchPlaceholder')}
            value={searchQuery}
            onChange={handleTableSearch}
            className="pl-8 w-full"
          />
        </div>
        <Button
          size="sm"
          variant="outline"
          className="flex items-center gap-1 ml-2"
          onClick={() => setIsDialogOpen(true)}
        >
          <Plus className="h-4 w-4" />
          {t('addColumn')}
        </Button>
        {/* 添加列对话框 */}
        <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>{t('addNewEvaluationColumn')}</DialogTitle>
            </DialogHeader>
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="column-label" className="text-right">
                  {t('columnName')}
                </Label>
                <Input
                  id="column-label"
                  value={newColumnLabel}
                  onChange={(e) => setNewColumnLabel(e.target.value)}
                  className="col-span-3"
                  placeholder={t('columnNamePlaceholder')}
                />
              </div>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setIsDialogOpen(false)}>{commonT('cancel')}</Button>
              <Button onClick={handleAddColumn}>{t('addAndSearch')}</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
        {/* 编辑列对话框 */}
        <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>{t('editEvaluationColumn')}</DialogTitle>
            </DialogHeader>
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-column-label" className="text-right">
                  {t('columnName')}
                </Label>
                <Input
                  id="edit-column-label"
                  value={editColumnLabel}
                  onChange={(e) => setEditColumnLabel(e.target.value)}
                  className="col-span-3"
                  placeholder={t('columnNamePlaceholder')}
                />
              </div>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setIsEditDialogOpen(false)}>{commonT('cancel')}</Button>
              <Button onClick={handleEditColumn}>{t('editAndSearch')}</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
        {/* 删除列确认对话框 */}
        <AlertDialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>{t('deleteEvaluationColumn')}</AlertDialogTitle>
              <AlertDialogDescription>
                {t('deleteConfirmation')}
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel>{commonT('cancel')}</AlertDialogCancel>
              <AlertDialogAction onClick={handleDeleteColumn} className="bg-red-500 hover:bg-red-600">
                {commonT('delete')}
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </div>
      {isLoading && (
        <div className="py-10 flex flex-col items-center justify-center text-gray-500">
          <Loader2 className="w-8 h-8 mb-2 animate-spin" />
          <p>Loading...</p>
        </div>
      )}
      {!isLoading && (
        <Table>
          <TableHeader>
            <TableRow>
              {searchScoreKeys?.map((rule, index) => (
                <TableHead key={`search-${index}`}>{rule}</TableHead>
              ))}
              {matchingRulesKeys?.map((rule, index) => (
                <TableHead key={`match-${index}`}>
                  <span>{rule}</span>
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button variant="ghost" className="h-8 w-8 p-0">
                        <MoreVertical className="h-4 w-4" />
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                      <DropdownMenuItem onClick={() => openEditColumnDialog(rule)}>
                        <Edit className="mr-2 h-4 w-4" />
                        {commonT('edit')}
                      </DropdownMenuItem>
                      <DropdownMenuItem onClick={() => openDeleteColumnDialog(rule)}>
                        <Trash2 className="mr-2 h-4 w-4" />
                        {commonT('delete')}
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                </TableHead>
              ))}
              <TableHead className="text-right">{t('annotation')}</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {(filteredData && filteredData.length > 0 ? filteredData : []).map((item, index) => {
              // 准备搜索结果数据
              const searchCells = searchScoreKeys?.map((key, cellIndex) => {
                return (
                  <TableCell key={`search-${index}-${cellIndex}`}>
                    {Array.isArray(item.search_result[key]) ? (
                      <div className="flex flex-wrap gap-1">
                        {item.search_result[key].map((value: string, i: number) => (
                          <Badge key={`${index}-${cellIndex}-${i}`} variant="secondary"
                          className="bg-blue-500 text-white dark:bg-blue-600">
                            {value}
                          </Badge>
                        ))}
                      </div>
                    ) : (
                      item.search_result[key] || 'searching...'
                    )}
                  </TableCell>
                )
              });

              // 准备匹配规则数据
              const matchCells = matchingRulesKeys?.map((key, cellIndex) => (
                <TableCell key={`match-${index}-${cellIndex}`}>
                  {item.match_score[key] || 'searching...'}
                </TableCell>
              ));

              const operationCell = (
                <TableCell className="text-right">
                  <div className="flex justify-end space-x-2">
                    {
                      loadingState && loadingState.resultId === item.result_id ? (
                        <Button
                          size="sm"
                          variant={'outline'}
                        >
                          <Loader2 className="h-4 w-4 animate-spin" />
                        </Button>
                      ) : (
                        <Button
                          size="sm"
                          variant={item.user_verdict === 'APPROVED' ? 'default' : 'outline'}
                          className={item.user_verdict === 'APPROVED' ? 'bg-green-500 hover:bg-green-600' : ''}
                          onClick={() => handleAnnotation(item, 'compliant')}
                        >
                          <Check className="h-4 w-4" />
                        </Button>
                      )
                    }
                    {
                      loadingState && loadingState.resultId === item.result_id ? (
                        <Button
                          size="sm"
                          variant={'outline'}
                        >
                          <Loader2 className="h-4 w-4 animate-spin" />
                        </Button>
                      ) : (
                        <Button
                          size="sm"
                          variant={item.user_verdict === 'REJECTED' ? 'default' : 'outline'}
                          className={item.user_verdict === 'REJECTED' ? 'bg-red-500 hover:bg-red-600' : ''}
                          onClick={() => handleAnnotation(item, 'non-compliant')}
                        >
                          <X className="h-4 w-4" />
                        </Button>
                      )
                    }
                  </div>
                </TableCell>
              );

              // 返回包含两种数据的完整行
              return (
                <TableRow key={index}>
                  {searchCells}
                  {matchCells}
                  {operationCell}
                </TableRow>
              );
            })}

            {filteredData && filteredData.length === 0 && (
              <TableRow>
                <TableCell colSpan={(searchScoreKeys?.length || 0) + (matchingRulesKeys?.length || 0)} className="text-center py-10">
                  {searchQuery.trim() ? t('noProjectsFound') : 'No data available'}
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      )}
    </div>
  );
}